<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="优惠劵名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入优惠劵名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="第三方平台ID" prop="thirdPlateId">
              <el-input v-model="queryParams.thirdPlateId" placeholder="请输入第三方平台ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" clearable>
                <el-option v-for="dict in coupon_business_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="优惠卷类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择优惠卷类型" clearable>
                <el-option v-for="dict in coupon_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="优惠卷状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择优惠卷状态" clearable>
                <el-option v-for="dict in coupon_template_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTimes">
              <el-date-picker
                v-model="queryParams.params.createTimes"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-240px"
                end-placeholder="结束日期"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['tearoom:couponTemplate:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['tearoom:couponTemplate:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['tearoom:couponTemplate:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['tearoom:couponTemplate:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- Tab 选项：真正的内容在 Lab -->
      <el-tabs v-model="activeTab" type="card" @tab-change="onTabChange">
        <el-tab-pane v-for="tab in plateTypeTabs" :key="tab.value" :label="tab.label" :name="tab.value" />
      </el-tabs>

      <el-table v-loading="loading" :data="couponTemplateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" v-if="false" />
        <el-table-column label="优惠劵名称" align="center" prop="name" width="150px" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="coupon_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="优惠" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="coupon_discount_type" :value="scope.row.type" />
            <div>{{ discountFormat(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="业务类型" align="center" prop="businessType">
          <template #default="scope">
            <dict-tag :options="coupon_business_type" :value="scope.row.businessType" />
          </template>
        </el-table-column>
        <el-table-column label="平台类型" align="center" prop="plateType">
          <template #default="scope">
            <dict-tag :options="coupon_plate_type" :value="scope.row.plateType" />
          </template>
        </el-table-column>
        <el-table-column label="第三方平台ID" align="center" prop="thirdPlateId" width="150px" />
        <!-- <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="coupon_status" :value="scope.row.status" />
          </template>
        </el-table-column> -->
        <el-table-column label="领取方式" align="center" prop="takeType">
          <template #default="scope">
            <dict-tag :options="coupon_take_type" :value="scope.row.takeType" />
          </template>
        </el-table-column>
        <el-table-column label="范围" align="center" prop="productScope">
          <template #default="scope">
            <dict-tag :options="coupon_product_scope" :value="scope.row.productScope" />
          </template>
        </el-table-column>
        <el-table-column :formatter="validityTypeFormat" align="center" label="使用时间" prop="validityType" width="185px" />
        <el-table-column :formatter="totalCountFormat" label="发放数量" align="center" prop="totalCount" />
        <el-table-column :formatter="remainedCountFormat" label="剩余数量" align="center" prop="totalCount" />
        <el-table-column :formatter="takeLimitCountFormat" align="center" label="领取上限" prop="takeLimitCount" width="120px" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="remark" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['tearoom:couponTemplate:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['tearoom:couponTemplate:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改优惠劵模板对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="750px" append-to-body>
      <el-form ref="couponTemplateFormRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="优惠劵名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠劵名称" />
        </el-form-item>
        <el-form-item label="优惠劵描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入优惠劵描述" />
        </el-form-item>
        <el-form-item label="平台类型" prop="plateType">
          <el-select v-model="form.plateType" placeholder="请选择平台类型" clearable>
            <el-option v-for="dict in coupon_plate_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="第三方平台ID" prop="thirdPlateId" v-if="form.plateType != CouponTemplatePlateTypeEnum.ZY.type">
          <el-input v-model="form.thirdPlateId" placeholder="请输入第三方平台ID" />
        </el-form-item>
        <el-form-item label="优惠卷类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="dict in coupon_type" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠卷范围" prop="productScope">
          <el-radio-group v-model="form.productScope">
            <el-radio v-for="dict in coupon_product_scope" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠卷业务类型" prop="businessType">
          <el-radio-group v-model="form.businessType">
            <el-radio v-for="dict in coupon_business_type" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="门店选择" prop="regionalIds" v-if="form.productScope === CouponProceductScopeTypeEnum.MD.type">
          <el-select v-model="form.regionalIds" filterable clearable placeholder="请选择门店" :loading="loading" multiple>
            <el-option v-for="item in regionalList" :key="item.id" :label="item.groupName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.productScope === CouponProceductScopeTypeEnum.SP.type" label="空间" prop="roomIds">
          <RoomSelect v-model="form.roomIds" />
        </el-form-item>
        <el-form-item label="小时数" prop="hourCount" v-if="form.type === CouponTemplateTypeEnum.XSJ.type">
          <el-input-number v-model="form.hourCount" :min="0.5" :precision="1" :step="0.5" class="mr-2 !w-400px" placeholder="请设置小时数" />
          小时
        </el-form-item>
        <el-form-item
          v-if="form.type === CouponTemplateTypeEnum.XSJ.type || form.type === CouponTemplateTypeEnum.DJJ.type"
          label="优惠券面额"
          prop="discountPrice"
        >
          <el-input-number v-model="form.discountPrice" :min="0" :precision="2" class="mr-2 !w-400px" placeholder="请输入优惠金额，单位：元" />
          元
        </el-form-item>
        <el-form-item v-if="form.type === CouponTemplateTypeEnum.ZKJ.type" label="优惠券折扣" prop="discountPercent">
          <el-input-number
            v-model="form.discountPercent"
            :max="9.9"
            :min="1"
            :precision="1"
            class="mr-2 !w-400px"
            placeholder="优惠券折扣不能小于 1 折，且不可大于 9.9 折"
          />
          折
        </el-form-item>
        <el-form-item v-if="form.type === CouponTemplateTypeEnum.ZKJ.type" label="最多优惠" prop="discountLimitPrice">
          <el-input-number v-model="form.discountLimitPrice" :min="0" :precision="2" class="mr-2 !w-400px" placeholder="请输入最多优惠" />
          元
        </el-form-item>
        <el-form-item
          label="满多少元可以使用"
          prop="usePrice"
          v-if="form.type === CouponTemplateTypeEnum.DJJ.type || form.type === CouponTemplateTypeEnum.ZKJ.type"
        >
          <el-input-number v-model="form.usePrice" :min="0" :precision="2" class="mr-2 !w-400px" placeholder="无门槛请设为 0" />
          元
        </el-form-item>
        <el-form-item label="领取方式" prop="takeType">
          <el-radio-group v-model="form.takeType">
            <el-radio v-for="dict in coupon_take_type" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.takeType === 1" label="发放数量" prop="totalCount">
          <el-input-number
            v-model="form.totalCount"
            :min="-1"
            :precision="0"
            class="mr-2 !w-400px"
            placeholder="发放数量，没有之后不能领取或发放，-1 为不限制"
          />
          张
        </el-form-item>
        <el-form-item v-if="form.takeType === 1" label="每人限领个数" prop="takeLimitCount">
          <el-input-number v-model="form.takeLimitCount" :min="-1" :precision="0" class="mr-2 !w-400px" placeholder="设置为 -1 时，可无限领取" />
          张
        </el-form-item>
        <el-form-item label="有效期类型" prop="validityType">
          <el-radio-group v-model="form.validityType">
            <el-radio v-for="dict in coupon_validity_type" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.validityType === CouponTemplateValidityTypeEnum.DATE.type" label="固定日期" prop="validTimes">
          <el-date-picker
            v-model="form.validTimes"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
            type="datetimerange"
            value-format="x"
          />
        </el-form-item>
        <el-form-item v-if="form.validityType === CouponTemplateValidityTypeEnum.TERM.type" label="领取日期" prop="fixedStartTerm">
          第
          <el-input-number v-model="form.fixedStartTerm" :min="0" :precision="0" class="mx-2 !w-180px" placeholder="0为今天生效" />
          至
          <el-input-number v-model="form.fixedEndTerm" :min="0" :precision="0" class="mx-2 !w-180px" placeholder="结束天数" />
          天有效
        </el-form-item>

        <!-- 新增：使用时段(星期) -->
        <el-form-item label="可用日期" prop="validDaysMask">
          <el-checkbox-group v-model="form.validDaysMask">
            <el-checkbox v-for="day in weekDays" :key="day.value" :label="day.value" :disabled="day.value === 127">
              {{ day.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 新增：每天使用时间 -->
        <el-form-item label="可用时段" prop="useTimeRange">
          <el-time-picker
            v-model="form.useTimeRange"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="选择时间范围"
          >
          </el-time-picker>
          <div class="tip-text">留空表示全天可用</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CouponTemplate" lang="ts">
import {
  listCouponTemplate,
  getCouponTemplate,
  delCouponTemplate,
  addCouponTemplate,
  updateCouponTemplate,
  changeCouponStatus
} from '@/api/tearoom/couponTemplate';
import {
  CouponTemplateVO,
  CouponTemplateQuery,
  CouponTemplateForm,
  CouponTemplatePlateTypeEnum,
  CouponProceductScopeTypeEnum,
  CouponTemplateValidityTypeEnum,
  CouponTemplateTypeEnum
} from '@/api/tearoom/couponTemplate/types';
import RoomSelect from '@/views/tearoom/roomDetails/components/RoomSelect.vue';
import { convertToInteger, formatToFraction } from '@/utils/index';
import {
  discountFormat,
  remainedCountFormat,
  takeLimitCountFormat,
  totalCountFormat,
  validityTypeFormat
} from '@/views/tearoom/couponTemplate/formatter';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  coupon_type,
  coupon_product_scope,
  coupon_validity_type,
  coupon_take_type,
  coupon_status,
  coupon_discount_type,
  coupon_plate_type,
  coupon_template_status,
  coupon_business_type
} = toRefs<any>(
  proxy?.useDict(
    'coupon_type',
    'coupon_product_scope',
    'coupon_validity_type',
    'coupon_take_type',
    'coupon_status',
    'coupon_discount_type',
    'coupon_plate_type',
    'coupon_template_status',
    'coupon_business_type'
  )
);
import { RoomGroupVO, RoomDetailsVO } from '@/api/tearoom/roomDetails/types';
import { querygroupDetails } from '@/api/tearoom/roomDetails/index';
const regionalList = ref<RoomGroupVO[]>([]);

const couponTemplateList = ref<CouponTemplateVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const couponTemplateFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const activeTab = ref('all'); // Tab 筛选const activeTab = ref('all') // Tab 筛选
const plateTypeTabs = reactive([
  {
    label: '全部',
    value: 'all'
  },
  {
    label: '自营',
    value: '1'
  },
  {
    label: '美团',
    value: '2'
  },
  {
    label: '抖音',
    value: '3'
  },
  {
    label: '快手',
    value: '4'
  }
]);

// 星期选项配置
const weekDays = reactive([
  { label: '周一', value: 1 << 0 },
  { label: '周二', value: 1 << 1 },
  { label: '周三', value: 1 << 2 },
  { label: '周四', value: 1 << 3 },
  { label: '周五', value: 1 << 4 },
  { label: '周六', value: 1 << 5 },
  { label: '周日', value: 1 << 6 }
]);

const initFormData: CouponTemplateForm = {
  id: undefined,
  name: undefined,
  status: undefined,
  takeType: undefined,
  totalCount: undefined,
  takeLimitCount: undefined,
  takeCount: undefined,
  useCount: undefined,
  usePrice: undefined,
  productScope: undefined,
  productScopeValues: undefined,
  validityType: undefined,
  validStartTime: undefined,
  validEndTime: undefined,
  fixedStartTerm: undefined,
  fixedEndTerm: undefined,
  type: undefined,
  plateType: undefined,
  thirdPlateId: undefined,
  hourCount: undefined,
  discountType: undefined,
  discountPercent: undefined,
  discountPrice: undefined,
  discountLimitPrice: undefined,
  remark: undefined,
  validTimes: [],
  roomIds: [],
  regionalIds: [],
  validDays: undefined, // 默认为每天可用
  validDaysMask: [],
  useTimeRange: null, // 时间范围 [start, end]
  useStartTime: undefined,
  useEndTime: undefined
};
const data = reactive<PageData<CouponTemplateForm, CouponTemplateQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    status: undefined,
    takeType: undefined,
    totalCount: undefined,
    takeLimitCount: undefined,
    takeCount: undefined,
    useCount: undefined,
    usePrice: undefined,
    productScope: undefined,
    productScopeValues: undefined,
    validityType: undefined,
    validStartTime: undefined,
    validEndTime: undefined,
    fixedStartTerm: undefined,
    fixedEndTerm: undefined,
    type: undefined,
    plateType: undefined,
    thirdPlateId: undefined,
    hourCount: undefined,
    discountType: undefined,
    discountPercent: undefined,
    discountPrice: undefined,
    discountLimitPrice: undefined,
    params: {
      createTimes: []
    },
    validTimes: [],
    roomIds: [],
    regionalIds: []
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '优惠劵名称不能为空', trigger: 'blur' }],
    discountPrice: [{ required: true, message: '优惠劵面额不能为空', trigger: 'blur' }],
    plateType: [{ required: true, message: '平台类型不能为空', trigger: 'blur' }],
    thirdPlateId: [{ required: true, message: '第三方平台ID不能为空', trigger: 'blur' }],
    hourCount: [{ required: true, message: '小时数不能为空', trigger: 'blur' }],
    discountPercent: [{ required: true, message: '优惠券折扣不能为空', trigger: 'blur' }],
    discountLimitPrice: [{ required: true, message: '最多优惠不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    takeType: [{ required: true, message: '领取方式不能为空', trigger: 'change' }],
    totalCount: [{ required: true, message: '发放数量, -1 - 则表示不限制不能为空', trigger: 'blur' }],
    takeLimitCount: [{ required: true, message: '每人限领个数, -1 - 则表示不限制不能为空', trigger: 'blur' }],
    takeCount: [{ required: true, message: '领取优惠券的数量不能为空', trigger: 'blur' }],
    useCount: [{ required: true, message: '使用优惠券的次数不能为空', trigger: 'blur' }],
    usePrice: [{ required: true, message: '满多少金额可用不能为空', trigger: 'blur' }],
    productScope: [{ required: true, message: '优惠卷范围不能为空', trigger: 'change' }],
    validityType: [{ required: true, message: '有效日期类型不能为空', trigger: 'change' }],
    type: [{ required: true, message: '优惠卷类型不能为空', trigger: 'change' }],
    businessType: [{ required: true, message: '优惠卷业务类型不能为空', trigger: 'change' }],
    fixedStartTerm: [{ required: true, message: '领取日期不能为空', trigger: 'change' }],
    validTimes: [{ required: true, message: '固定日期不能为空', trigger: 'change' }],
    roomIds: [{ required: true, message: '空间不能为空', trigger: 'change' }],
    regionalIds: [{ required: true, message: '门店不能为空', trigger: 'change' }],
    validDaysMask: [{ required: true, message: '请选择可用星期', trigger: 'change' }],
    useTimeRange: [
      {
        validator: (rule, value, callback) => {
          if (value && value[0] >= value[1]) {
            callback(new Error('结束时间必须晚于开始时间'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询优惠劵模板列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCouponTemplate(queryParams.value);
  couponTemplateList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  couponTemplateFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CouponTemplateVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加优惠劵模板';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CouponTemplateVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCouponTemplate(_id);
  Object.assign(form.value, res.data);
  form.value = {
    ...res.data,
    discountPrice: formatToFraction(res.data.discountPrice),
    discountPercent: res.data.discountPercent !== undefined ? res.data.discountPercent / 10.0 : undefined,
    discountLimitPrice: formatToFraction(res.data.discountLimitPrice),
    usePrice: formatToFraction(res.data.usePrice),
    validTimes: [res.data.validStartTime, res.data.validEndTime],
    useTimeRange: res.data.useStartTime && res.data.useEndTime ? [res.data.useStartTime, res.data.useEndTime] : []
  };
  //设置优惠卷范围
  updateSetScopeValues(res.data);
  // 回显星期选择
  if (res.data.validDays) {
    form.value.validDaysMask = [];
    // 解析位掩码
    weekDays.forEach((day) => {
      if (res.data.validDays & day.value) {
        form.value.validDaysMask.push(day.value);
      }
    });
  }
  dialog.visible = true;
  dialog.title = '修改优惠劵模板';
};

/** 提交按钮 */
const submitForm = () => {
  couponTemplateFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const data = {
        ...form.value,
        discountPrice: convertToInteger(form.value.discountPrice),
        discountPercent: form.value.discountPercent !== undefined ? form.value.discountPercent * 10 : undefined,
        discountLimitPrice: convertToInteger(form.value.discountLimitPrice),
        usePrice: convertToInteger(form.value.usePrice),
        validStartTime: form.value.validTimes && form.value.validTimes.length === 2 ? form.value.validTimes[0] : undefined,
        validEndTime: form.value.validTimes && form.value.validTimes.length === 2 ? form.value.validTimes[1] : undefined,
        totalCount: form.value.takeType === 1 ? form.value.totalCount : -1,
        takeLimitCount: form.value.takeType === 1 ? form.value.takeLimitCount : -1,
        useStartTime: form.value.useTimeRange ? form.value.useTimeRange[0] : null,
        useEndTime: form.value.useTimeRange ? form.value.useTimeRange[1] : null,
        validDays:
          form.value.validDaysMask && form.value.validDaysMask.length > 0 ? form.value.validDaysMask.reduce((mask, day) => mask | day, 0) : 127
      } as unknown as CouponTemplateVO;
      // 设置优惠卷范围
      setProductScopeValues(data);
      if (data.id) {
        await updateCouponTemplate(data).finally(() => (buttonLoading.value = false));
      } else {
        await addCouponTemplate(data).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 设置优惠卷范围 */
function setProductScopeValues(data: CouponTemplateVO) {
  switch (form.value.productScope) {
    case CouponProceductScopeTypeEnum.MD.type:
      data.productScopeValues = form.value.regionalIds;
      break;
    case CouponProceductScopeTypeEnum.SP.type:
      data.productScopeValues = Array.isArray(form.value.roomIds) ? form.value.roomIds : [form.value.roomIds];
      break;
    default:
      break;
  }
}

/** 设置优惠卷范围 */
function updateSetScopeValues(data: CouponTemplateVO) {
  switch (data.productScope) {
    case CouponProceductScopeTypeEnum.MD.type:
      form.value.regionalIds = data.productScopeValues;
      break;
    case CouponProceductScopeTypeEnum.SP.type:
      form.value.roomIds = data.productScopeValues;
      break;
    default:
      break;
  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: CouponTemplateVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除优惠劵模板编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delCouponTemplate(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'tearoom/couponTemplate/export',
    {
      ...queryParams.value
    },
    `couponTemplate_${new Date().getTime()}.xlsx`
  );
};

// 获取门店数据下拉对象
const fetchRegionalListData = async () => {
  loading.value = true;
  const response = await querygroupDetails();
  regionalList.value = response.data;
  loading.value = false;
};

/** 优惠券开关状态修改  */
const handleStatusChange = async (row: CouponTemplateVO) => {
  let text = row.status == 1 ? '开启' : '关闭';
  try {
    await proxy?.$modal.confirm('确认要"' + text + row.name + '"优惠卷吗?');
    await changeCouponStatus(row.id, row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch (err) {
    row.status = row.status == 1 ? 0 : 1;
  }
};

/** tab 切换 */
const onTabChange = (tabName) => {
  queryParams.value.plateType = tabName === 'all' ? undefined : tabName;
  getList();
};

onMounted(() => {
  getList();
  fetchRegionalListData();
});
</script>

<style scoped>
.tip-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  margin-left: 5px;
}
</style>
